package com.atguigu.tingshu.account.service.impl;

import com.atguigu.tingshu.account.mapper.RechargeInfoMapper;
import com.atguigu.tingshu.account.mapper.UserAccountMapper;
import com.atguigu.tingshu.account.service.RechargeInfoService;
import com.atguigu.tingshu.account.service.UserAccountService;
import com.atguigu.tingshu.common.constant.SystemConstant;
import com.atguigu.tingshu.model.account.RechargeInfo;
import com.atguigu.tingshu.vo.account.RechargeInfoVo;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.UUID;

@Service
@SuppressWarnings({"all"})
public class RechargeInfoServiceImpl extends ServiceImpl<RechargeInfoMapper, RechargeInfo> implements RechargeInfoService {

	@Autowired
	private RechargeInfoMapper rechargeInfoMapper;

	@Autowired
	private UserAccountMapper userAccountMapper;

	@Autowired
	private UserAccountService userAccountService;
	@Override
	public RechargeInfo getRechargeInfo(String orderNo) {
		return rechargeInfoMapper.selectOne(new LambdaQueryWrapper<RechargeInfo>().eq(RechargeInfo::getOrderNo,orderNo));
	}

	@Override
	public String submitRecharge(RechargeInfoVo rechargeInfoVo, Long userId) {
		//创建对象
		RechargeInfo rechargeInfo = new RechargeInfo();
		//赋值
		rechargeInfo.setUserId(userId);
		rechargeInfo.setRechargeAmount(rechargeInfoVo.getAmount());
		rechargeInfo.setPayWay(rechargeInfoVo.getPayWay());
		rechargeInfo.setRechargeStatus(SystemConstant.ORDER_STATUS_UNPAID);
		//订单编号
		String orderNo = UUID.randomUUID().toString().replaceAll("-", "");
		rechargeInfo.setOrderNo(orderNo);
		this.rechargeInfoMapper.insert(rechargeInfo);
		//返回订单编号
		return orderNo;
	}

	@Override
	public void updateRechargeInfo(String orderNo) {
		//修改充值状态
		RechargeInfo rechargeInfo = rechargeInfoMapper.selectOne(new LambdaQueryWrapper<RechargeInfo>().eq(RechargeInfo::getOrderNo, orderNo));
		//判断
		if (null != rechargeInfo && rechargeInfo.getRechargeStatus().equals(SystemConstant.ORDER_STATUS_UNPAID)){
			//修改状态
			rechargeInfo.setRechargeStatus(SystemConstant.ORDER_STATUS_PAID);
			//调用修改方法
			this.updateById(rechargeInfo);
			//需要增加账户余额
			userAccountMapper.addAccountAmout(rechargeInfo.getRechargeAmount(),rechargeInfo.getUserId());
			//需要记录充值信息
			userAccountService.addUserAccountDetail(rechargeInfo.getUserId(),"余额充值",SystemConstant.ACCOUNT_TRADE_TYPE_DEPOSIT,rechargeInfo.getRechargeAmount(),rechargeInfo.getOrderNo());
		}
	}
}
